<template>
  <div class="app-main-container">
    <!-- <div class="app-main-title">门票订单</div> -->
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getList(1)"
      @clear="clear"
    >
      <template #btns>
        <el-button
          v-if="meta.indexOf('TicketOrderExcel') > -1"
          :loading="exportLoading"
          type="primary"
          @click="handleExport"
        >导出</el-button>
      </template>
    </QueryForm>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table doumee-element-tableb"
    >
      <el-table-column
        align="center"
        label="订单号"
        min-width="220"
        show-overflow-tooltip
      >
        <template v-slot="scope">
          <span class="ckxqBtn" @click="handleDetail(scope.row.orderId)">{{
            scope.row.orderId
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="订单详情"
        min-width="200"
        show-overflow-tooltip
        prop="orderInfo"
      />
      <el-table-column
        align="center"
        label="订单合计"
        prop="allPrice"
        min-width="100"
      />
      <el-table-column align="center" label="订单来源" min-width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.channelType == '01'">小程序</span>
          <span v-else-if="scope.row.channelType == '02'">场馆pc端</span>
          <span v-else-if="scope.row.channelType == '05'">自助机</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="支付方式"
        min-width="140"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.payMethodName }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="会员信息"
        prop="memberName"
        min-width="240"
        show-overflow-tooltip
      />
      <!-- <el-table-column
        align="center"
        label="使用日期"
        prop="useDate"
        show-overflow-tooltip
        width="120"
      /> -->
      <el-table-column
        label="备注"
        min-width="200"
        align="center"
        prop="remarks"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="操作员"
        prop="creator"
        min-width="100"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createTime"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="订单状态"
        min-width="100"
        show-overflow-tooltip
        fixed="right"
      >
        <template slot-scope="scope">
          <span
            v-if="scope.row.status == '0'"
            class="primaryColor pointer"
            @click="getOrderType(scope.row.orderId)"
          >待支付</span>
          <span v-else>{{ scope.row.statusName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        min-width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <div
            v-if="scope.row.status == '0' || scope.row.status == '3'"
            class="flex-cc"
          >
            <!-- <el-button
              v-if="scope.row.status == '0'"
              v-preventReClick
              type="text"
              @click="getOrderType(scope.row.orderId)"
            >查询支付状态</el-button> -->
            <el-button
              v-if="
                (scope.row.status == '0' &&
                  meta.indexOf('TicketOrderPayContinue') > -1) ||
                  (scope.row.status == '3' &&
                    meta.indexOf('TicketOrderCancel') > -1)
              "
              v-preventReClick
              type="text"
              @click="firstAction(scope.row.orderId, scope.row.status)"
            >{{
              scope.row.status == "0" ? "继续支付" : "取消订单"
            }}</el-button>
            <el-button
              v-if="
                (scope.row.status == '0' &&
                  meta.indexOf('TicketOrderPayCancel') > -1) ||
                  (scope.row.status == '3' &&
                    meta.indexOf('TicketPrinterOrder') > -1)
              "
              v-preventReClick
              type="text"
              @click="secondAction(scope.row.orderId, scope.row.status)"
            >{{
              scope.row.status == "0" ? "取消购买" : "打印小票"
            }}</el-button>
          </div>
          <div v-else class="flex-cc">-</div>
        </template>
      </el-table-column>
    </el-table>
    <!-- <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page.sync="pagination.page"
        :total="total"
        hide-on-single-page
        @current-change="getList"
      />
    </div> -->
    <Paginations
      :total="total"
      :page="pagination.page"
      @SizeChange="pageSizeChange"
      @current-change="getList"
    />
    <orderDialog ref="child" @orderSuccess="getList" />
    <orderDetail ref="orderDetail" />
  </div>
</template>

<script>
import {
  getProjectList,
  ticketOrders,
  ticketBuyCancel,
  ticketOrderCancel,
  orderType,
  allConfigList,
  printOrder,
  ticketOrderExport,
  getOrderTypeQuery
} from '@/api'
import { parseTime } from '@/utils'
import orderDialog from '@/components/order'
import Paginations from '@/components/paginations/paginations'
import QueryForm from '@/components/QueryForm'
import orderDetail from './orderDetail'
import { TJshortcuts } from '@/utils/config'
export default {
  name: 'TicketOrder',
  components: {
    orderDialog,
    QueryForm,
    orderDetail,
    Paginations
  },
  data() {
    return {
      exportLoading: false,
      queryFormConfig: {
        formItems: [{
          filed: 'orderId',
          type: 'input',
          label: '订单编号',
          placeholder: '请输入订单编号',
          clearable: true
        }, {
          filed: 'projectId',
          type: 'select',
          label: '适用项目',
          placeholder: '请选择项目',
          clearable: true,
          options: []
        }, {
          filed: 'ticketName',
          type: 'input',
          label: '门票名称',
          placeholder: '请输入门票名称',
          clearable: true
        }, {
          filed: 'channelType',
          type: 'select',
          label: '订单来源',
          placeholder: '请选择订单来源',
          clearable: true,
          options: [
            { value: '01', label: '小程序' },
            { value: '02', label: '场馆pc端' },
            { value: '05', label: '自助机' }
          ]
        }, {
          filed: 'payMethod',
          type: 'select',
          label: '支付方式',
          clearable: true,
          options: []
        }, {
          filed: 'payStatus',
          type: 'select',
          label: '订单状态',
          placeholder: '请选择订单状态',
          clearable: true,
          labelCode: 'name',
          options: []
        },
        {
          filed: 'memberNameOrPhone',
          type: 'input',
          label: '会员信息',
          placeholder: '请输入会员姓名/手机号',
          clearable: true
        }, {
          filed: 'time',
          label: '下单日期',
          type: 'daterange',
          clearable: true,
          pickerOptions: {
            shortcuts: TJshortcuts
          }
        }],
        online: true
      },
      meta: [],
      payMessage: {},
      list: [],
      total: 0,
      pagination: {
        page: 1,
        rows: 10
      },
      listLoading: true,
      openStatus: [
        { value: '1', label: '正常营业' },
        { value: '0', label: '停业' }
      ],
      payTypes: [],
      orderStatuss: [
        { value: '0', label: '待支付' },
        { value: '1', label: '超时未支付' },
        { value: '2', label: '取消支付' },
        { value: '3', label: '支付成功' },
        { value: '4', label: '退款中' },
        { value: '5', label: '退款成功' }
      ],
      filters: {}
    }
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getInitData()
    allConfigList({ param: { type: '2', code: '1' }})
      .then((res) => {
        if (res.errorCode !== '000000') return
        this.payTypes = res.recordList
        const arr = res.recordList
        arr.forEach(e => {
          e.label = e.name
        })
        this.queryFormConfig.formItems[4].options = arr
      })
      .catch((err) => {
        console.log(err)
      })
    this.getOrderStatusList()
  },
  methods: {
    getOrderStatusList() {
      getOrderTypeQuery({ param: {}}).then(res => {
        this.queryFormConfig.formItems[5].options = res.recordList || []
      })
    },
    pageSizeChange(val) {
      this.pagination.rows = val
      this.getList(1)
    },
    handleExport() {
      const { filters } = this
      if (filters.time) {
        filters.startDate = filters.time[0]
        filters.endDate = filters.time[1]
      } else {
        filters.startDate = ''
        filters.endDate = ''
      }
      this.exportLoading = true
      ticketOrderExport({
        param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        }
      })
        .then((res) => {
          this.exportLoading = false
          if (res.errorCode === '000000') {
            const a = document.createElement('a') // 创建一个a标签元素
            a.style.display = 'none' // 设置元素不可见
            a.href = res.record.showUrl // 设置下载地址
            document.body.appendChild(a) // 加入
            a.click() // 触发点击,下载
            document.body.removeChild(a) //
            this.$message.success('导出成功')
          }
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
    handleDetail(id) {
      // this.$router.push({ name: 'ticketOrderDetail', query: { id }})
      this.$refs.orderDetail.getTicketOrderDetail(id)
    },
    getOrderType(orderId) {
      orderType({
        param: {
          orderId
        }
      })
        .then((res) => {
          const str = res.record.msg
          if (res.errorCode === '000000') {
            if (res.record.code === '0') {
              this.$message.success(str)
              this.getList(1)
            } else if (res.record.code === '2') {
              this.$message.info(str)
            } else {
              this.$message.error(str)
              this.getList(1)
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    nameWithPayMethod(payM) {
      const temp = this.payTypes.find(item => item.value === payM)
      return temp ? temp.name : ''
      // for (const item of this.payTypes) {
      //   if (item.value === payM) {
      //     return item.name
      //   }
      // }
      // return '-'
    },
    orderStatus(status) {
      const temp = this.orderStatuss.find(item => item.value === status)
      return temp ? temp.label : ''
    },
    getInitData() {
      getProjectList({
        param: {
          venueId: sessionStorage.getItem('venueId'),
          projectName: '',
          type: '1',
          status: ''
        }
      }).then((res) => {
        if (res.errorCode !== '000000') return
        const arr = res.recordList
        arr.forEach(e => {
          e.label = e.projectName
          e.value = e.id
        })
        // this.projectList = arr
        this.queryFormConfig.formItems[1].options = arr
        // this.projectList = res.recordList
      })
      this.getList()
    },
    getList(page) {
      const { filters, pagination } = this
      if (page) {
        pagination.page = page
        this.pagination.page = Number(page)
      }
      pagination.firstQueryTime = parseTime(new Date())
      if (filters.time) {
        filters.startDate = filters.time[0]
        filters.endDate = filters.time[1]
      } else {
        filters.startDate = ''
        filters.endDate = ''
      }
      this.listLoading = true
      ticketOrders({
        pagination, param: {
          ...filters,
          venueId: sessionStorage.getItem('venueId')
        }
      }).then(res => {
        this.listLoading = false
        if (res.errorCode === '000000') {
          this.list = res.recordList
          this.total = res.totalCount
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    clear() {
      this.filters = {}
      this.getList(1)
    },
    firstAction(id, status) {
      if (status === '0') {
        // 继续支付
        this.$refs.child.continuePay(id, 'ticketOrder')
      } else {
        // 取消订单
        this.$alert('确定要取消该订单？', '警告', {
          confirmButtonText: '确定',
          callback: (action) => {
            if (action === 'confirm') {
              ticketOrderCancel({ param: { id }})
                .then((res) => {
                  if (res.errorCode !== '000000') return
                  this.getList(1)
                })
            }
          }
        })
      }
    },
    secondAction(id, status) {
      if (status === '0') {
        // 取消购买
        this.$alert('确定要取消购买？', '警告', {
          confirmButtonText: '确定',
          callback: (action) => {
            if (action === 'confirm') {
              ticketBuyCancel({ param: { id }})
                .then((res) => {
                  if (res.errorCode !== '000000') return
                  this.getList(1)
                })
            }
          }
        })
      } else {
        this.printTC(id)
      }
    },
    printTC(id) {
      printOrder({
        param: {
          contentMap: {},
          venueId: sessionStorage.getItem('venueId'),
          workId: id,
          templateCode: 'TICKETTPML'
        }
      })
        .then(res => {
          console.log(res)
        })
    }
  }
}
</script>

<style lang='scss' scoped>
.division-line {
  text-align: center;
  display: inline-block;
  color: #999;
  width: 20px;
}
.pay-style {
  min-width: 80px;
  padding-left: 5px;
  padding-right: 5px;
  height: 30px;
  font-size: 15px;
  line-height: 1px;
  vertical-align: middle;
}
.slelect-pay-style {
  background-color: #1943a9;
  color: #fff;
}
.normal-pay-style {
  border: 1px solid #d8d8d8;
  background-color: #fff;
  color: #222;
}
.messgae-style {
  color: #dd0707;
}
.price-style {
  font-size: 17px;
  font-weight: 500;
}
.unit-style {
  margin-right: 20px;
}
.bottom-speace-style {
  margin-bottom: 10px;
}
.card-message {
  margin-bottom: 10px;
  background-color: #f2f2f2;
  height: 60px;
  line-height: 20px;
  .first-line {
    height: 30px;
    padding: 5px;
    .message-title-style {
      color: #999;
    }
    .card-name-style {
      display: inline-block;
      border: 1px #999 solid;
      border-radius: 4px;
      background-color: #fff;
      font-size: 12px;
      padding-left: 5px;
      padding-right: 5px;
      height: 20px;
      text-align: center;
    }
    .close-style {
      font-size: 20px;
      float: right;
      margin-right: 5px;
      margin-top: -2px;
      padding: 0;
      border: 0px #999 solid;
    }
    .message-value-style {
      margin-right: 15px;
      color: #222;
    }
  }
}
.footer-style {
  display: flex;
  justify-content: space-between;
  background-color: #f2f2f2;
  margin: -10px -20px -30px;
  height: 50px;
  .bottom-left {
    margin-left: 20px;
    height: 20px;
    margin-top: 15px;
    .sum-title-style {
      font-size: 15px;
      color: #222;
    }
    .sum-pay-value-style {
      font-size: 17px;
      font-weight: 500;
      color: #dd0707;
    }
    .dis-title-style {
      font-size: 14px;
      color: #222;
    }
    .discoun-style {
      font-size: 16px;
      color: #dd0707;
    }
  }
  .bottom-right {
    margin-right: 20px;
    margin-top: 10px;
    height: 30px;
    .pay-action-style {
      width: 100px;
      height: 30px;
      font-size: 15px;
      line-height: 1px;
      vertical-align: middle;
    }
  }
}
</style>
